package cn.com.gridinfo.sooc.utils.versionHttp;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;



/**
 * 文件下载类
 */
public class HttpDownLoader {
    private URL url = null;

    /**
     * 下载并保存文件的步骤
     * 1,查看原来目录上有没有这个文件
     * 2,没有的话就下载得到文件的inputstream流
     * 3，然后一个集合操作，建一个路径，建一个文件，把inputstream放到outputstream中去,返回一个文件
     * 4,下载其实已经结束了，只是还要看看有没有明显的错误
     *
     * @param urlString 下载路径
     * @param path      保存路径
     * @param fileName  保存文件的名字
     * @return
     * @throws IOException
     */
    public String downloadfile(String urlString, String path, String fileName) throws IOException {

        InputStream inputStream = null;
        int nameIndex = urlString.lastIndexOf("/");
        String webName = urlString.substring(nameIndex + 1);
        int typeIndex = webName.lastIndexOf(".");
        String type = webName.substring(typeIndex + 1);
        if (fileName == null) {
            fileName = webName;
        } else {
            if (!fileName.contains(".")) {
                fileName += "." + type;
            }
        }
        try {
            FileUtils fileUtils = new FileUtils();
            String filePath = path + fileName;
            if (fileUtils.isFileExist(filePath)) {
                return "100";
            }

            inputStream = getInputStreamFromUrl(urlString);
            File resultfile = fileUtils.writeToSDFromInput(path, fileName,
                    inputStream);
            // 如果现在还没有这个文件的话就说明没有下载到了
            if (resultfile != null) {
                return "200";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        } finally {
            inputStream.close();//记得关闭
        }
        return "0";
    }

    public InputStream getInputStreamFromUrl(String urlStr)
            throws MalformedURLException, IOException {
        url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        InputStream inputStream = urlConn.getInputStream();
        return inputStream;
    }
}  